<script setup>
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { ref } from 'vue'
	import { useUserStore } from '@/store/user'
	import { parseTime } from '@/utils/common'
	import { getReportList, getDictType } from '@/api/report'
	import { getAddressAfter } from '@/api/login'
	
	const user = useUserStore()
	const loading = ref(false)
	const loadStatus = ref('loadmore')
	const query = ref({
		sponsorName: '',
		startTime: '',
		areaId: user.addressIds[2],
		type: '',
		checkType: '', 
		current: 1,
		size: 20,
	})
	const triggered = ref(false)
	const total = ref(0)
	const list = ref([])
	let refreshId = undefined
	const style = {
		width: "140rpx",
		height: "76rpx",
		color: "#3c9cff",
		lineHeight: '76rpx',
		backgroundColor: "#fff",
		margin: "0rpx"
	}
	const timePicker = ref(null)
	const defaultTime = ref(Number(new Date()))
	const treePopup = ref(null)
	const selectOrg = ref(null)
	const selectOrgName = ref('')
	const orgTree = ref([])
	const auditPicker = ref(null)
	const auditColumns = [{label: '待审批', value: 0}, {label: '审批通过', value: 1}, {label: '审批驳回', value: 2}, {label: '已过期', value: 3}]
	const checkcheckShow = ref(null)
	const checkColumns = [{label: '待检查', value: 5}, {label: '已检查', value: 4}, {label: '已过期', value: 3}]
	const typeList = ref([])
	
	function getTree() {
		getAddressAfter(user.addressIds[2]).then(res => {
			let data = res.result || []
			orgTree.value = initTreeData(data)
		})
	}
	function initTreeData(data = []) {
		let arr = []
		data.forEach(item => {
			let newItem  = {
				label: item.areaName,
				value: item.areaId,
				expand: false
			}
			if(item.children && item.children.length) newItem.children = initTreeData(item.children)
			arr.push(newItem)
		})
		return arr
	}
	function getType() {
		getDictType('apply_banquets_types').then(res => {
			typeList.value = res.result || []
			search()
		})
	}
	function search() {
		triggered.value = true
	}
	function clearParams(name) {
		if(name === 'selectOrgName') {
			selectOrgName.value = ''
			query.value.areaId = user.addressIds[2]
		} else if(name === 'startTime') {
			defaultTime.value = Number(new Date())
			query.value.startTime = ''
		} else {
			query.value[name] = ''
		}
		triggered.value = true
	}
	function timeConfirm(e) {
		defaultTime.value = e.value
		query.value.startTime = parseTime(e.value, '{y}-{m}-{d}')
		triggered.value = true
	}
	function cancelTree() {
		treePopup.value.close()
	}
	function orgConfirm() {
		cancelTree()
		if(selectOrg.value) {
			query.value.areaId = selectOrg.value.value
			selectOrgName.value = selectOrg.value.label
			triggered.value = true
		}
	}
	function orgClick(item) {
		selectOrg.value = item
	}
	function orgExpand(item) {
		let curItem = treeFind(orgTree.value, item.value)
		if(curItem) curItem.expand = !curItem.expand
	}
	function treeFind(data = [], value) {
		let findItem = null
		for(let i = 0; i < data.length; i++) {
			let item = data[i]
			if(item.value === value) {
				findItem = item
				break
			} else if(item.children) {
				findItem = treeFind(item.children, value)
				if(findItem) break
			}
		}
		return findItem
	}
	function getAuditStatus(value) {
		let cur = auditColumns.find(item => item.value === value)
		if(cur) return cur.label
		else return ''
	}
	function getCheckStatus(value) {
		let cur = checkColumns.find(item => item.value === value)
		if(cur) return cur.label
		else return ''
	}
	function getApplyType(value) {
		let cur = typeList.value.find(item => item.value === value)
		if(cur) return cur.dictLabel
		else return '--'
	}
	function auditConfirm(e) {
		let item = e.value[0]
		query.value.approve = item.value
		triggered.value = true
	}
	function checkConfirm(e) {
		let item = e.value[0]
		query.value.checkType = item.value
		triggered.value = true
	}
	function refreshList() {
		if(loadStatus.value === 'loading') return
		loadStatus.value = 'loading'
		triggered.value = true
		list.value = []
		query.value.current = 1
		getReportList(query.value).then(res => {
			let result = res.result || {}
			let data = result.records || []
			data.forEach(item => item.expand = false)
			total.value = Number(result.total)
			list.value = data
			triggered.value = false
			let curLength = list.value.length || 0
			loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
		}).catch(() => {
			triggered.value = false
			loadStatus.value = 'loadmore'
		})
	}
	function lowerList(noReplace = true) {
		if(loadStatus.value == 'loadmore' && list.value.length < total.value || !noReplace){
			loadStatus.value = 'loading'
			query.value.current ++
			getReportList(query.value).then(res => {
				let result = res.result || {}
				let data = result.records || []
				data.forEach(item => item.expand = false)
				total.value = Number(result.total)
				if(noReplace) {
					list.value.push(...data)
				} else {
					const preList = list.value.slice(0, (query.value.current - 1) * query.value.size)
					list.value = preList.concat(data)
				}
				let curLength = list.value.length || 0
				loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
			}).catch(() => {
				query.value.current --
				loadStatus.value = 'loadmore'
			})
		}
	}
	function refreshItem(id) {
		let index = list.value.findIndex(item => item.applyId === id)
		if(index != -1) {
			query.value.current = Math.floor(index / query.value.size)
			lowerList(false)
		}
	}
	function expandMore(item) {
		item.expand = !item.expand
	}
	function goView(item) {
		uni.navigateTo({
			url: '/pages/Admin/preList/detail?id=' + item.applyId,
			success: () => {
				refreshId = item.applyId
			}
		})
	}
	
	onLoad(() => {
		getTree()
		getType()
	})
	onShow(() => {
		if(refreshId) {
			refreshItem(refreshId)
			refreshId = undefined
		}
	})
</script>

<template>
	<view :class="['app-container', user.theme]">
		<view class="app-head">
			<view class="search-box">
				<uv-search placeholder="请输入举办人姓名搜索" shape="square" searchIconSize="48" v-model="query.sponsorName" bgColor="#FFFFFF" borderColor="#fff"
					:showAction="true" @custom="search" @search="search" actionText="搜索" :actionStyle="style" height="72" :clearabled="false" 
					:custom-style="{borderRadius: '16rpx', overflow: 'hidden'}"></uv-search>
			</view>
			<view class="query-box">
				<view class="query-item large" @click="timePicker.open()">
					<text class="uv-line-1">{{query.startTime || '办宴时间'}}</text>
					<view v-if="query.startTime != ''" @click.stop="clearParams('startTime')">
						<uv-icon name="close" size="18" />
					</view>
					<uv-icon name="arrow-down-fill" color="#54504D" size="18" v-else />
				</view>
				<view class="query-item large" @click="treePopup.open()">
					<text class="uv-line-1">{{selectOrgName || '村社'}}</text>
					<view v-if="selectOrgName != ''" @click.stop="clearParams('selectOrgName')" >
						<uv-icon name="close" size="18" />
					</view>
					<uv-icon name="arrow-down-fill" color="#54504D" size="18" v-else />
				</view>
				<view class="query-item small" @click="auditPicker.open()">
					<text class="uv-line-1">{{getAuditStatus(query.type) || '审批状态'}}</text>
					<view v-if="query.type != ''" @click.stop="clearParams('type')">
						<uv-icon name="close" size="18" />
					</view>
					<uv-icon name="arrow-down-fill" color="#54504D" size="18" v-else />
				</view>
				<view class="query-item small" @click="checkcheckShow.open()">
					<text class="uv-line-1">{{getCheckStatus(query.checkType) || '检查状态'}}</text>
					<view v-if="query.checkType != ''" @click.stop="clearParams('checkType')">
						<uv-icon name="close" size="18" />
					</view>
					<uv-icon name="arrow-down-fill" color="#54504D" size="18" v-else />
				</view>
			</view>
		</view>
		<scroll-view scroll-y="true" class="app-content" refresher-enabled :refresher-triggered="triggered" @refresherrefresh="refreshList" lower-threshold="10" @scrolltolower="lowerList">
			<view class="content-list" v-if="list.length">
				<view class="content-box" v-for="(item, index) in list" :key="item.chefId">
					<view class="box-content">
						<view class="box-head">
							<view class="head-code">宴席编号：{{item.code || '--'}}</view>
							<view :class="['head-status', 'status-' + item.type]">
								<view class="status-circle"></view>
								<text>{{getAuditStatus(item.type)}}</text>
							</view>
						</view>
						<view class="box-time">
							<text>办宴时间：{{parseTime(item.startTime, '{y}-{m}-{d}')}}</text>
							<view :class="['time-status', 'status-' + item.checkType]">{{getCheckStatus(item.checkType)}}</view>
						</view>
						<view class="box-info">
							<text class="info-item">举办人：{{item.sponsorName || '--'}}</text>
							<text class="info-item">办宴类型：{{getApplyType(item.applyType)}}</text>
						</view>
						<template v-if="item.expand">
							<view class="box-info">
								<text class="info-item">聚餐人数：{{item.peopleNumber}}</text>
								<text class="info-item">办宴天数：{{item.days}}</text>
							</view>
							<view class="box-info">
								<text>村社：{{item.address}}</text>
							</view>
							<view class="box-info">
								<text>报备时间：{{item.createTime}}</text>
							</view>
						</template>
						<view class="expand-more" @click.stop="expandMore(item)">
							<template v-if="item.expand">
								<text>收起</text>
								<uv-icon name="arrow-up-fill" color="#ADB0BD" size="20" />
							</template>
							<template v-else>
								<text>展开</text>
								<uv-icon name="arrow-down-fill" color="#ADB0BD" size="20" />
							</template>
						</view>
					</view>
					<view class="box-bottom">
						<view class="bottom-btn" @click="goView(item)">详情</view>
						<template v-if="item.type === 0">
							<view class="line"></view>
							<view class="bottom-btn" @click="goView(item)">去审核</view>
						</template>
					</view>
				</view>
				<uv-load-more :status="loadStatus" :fontSize="user.theme? 36 : 28" :iconSize="user.theme? 48 : 34" isDot line marginTop="20" marginBottom="20">
				</uv-load-more>
			</view>
			<empty text="没有找到您搜索的宴席" v-else></empty>
		</scroll-view>
		
		<uv-popup ref="treePopup" mode="bottom">
			<view class="tree-popup">
				<view class="popup-head">
					<text @click="cancelTree" class="btn">取消</text>
					<text class="text">村社</text>
					<text @click="orgConfirm" class="btn primary">确定</text>
				</view>
				<scroll-view scroll-y="true" class="tree-scroll">
					<tree :data="orgTree" :value="selectOrg? selectOrg.value : 0" @clicKNode="orgClick" @changeExpand="orgExpand"></tree>
				</scroll-view>
			</view>
		</uv-popup>
		<uv-datetime-picker ref="timePicker" title="时间" :value="defaultTime" mode="date" visibleItemCount="8" @confirm="timeConfirm"></uv-datetime-picker>
		<uv-picker ref="auditPicker" title="审批状态" :columns="[auditColumns]" keyName="label" visibleItemCount="8" @confirm="auditConfirm"></uv-picker>
		<uv-picker ref="checkcheckShow" title="检查状态" :columns="[checkColumns]" keyName="label" visibleItemCount="8" @confirm="checkConfirm"></uv-picker>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		height: 100vh;
		.app-head{
			height: 220rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			gap: 16rpx;
			.search-box{
				padding: 0 32rpx;
				::v-deep .uv-search__content{
				    border-radius: 0rpx !important;
				}
				::v-deep .uv-search__content__input{
				   font-size: var(--theme-df) !important;
				   line-height: var(--theme-df-line) !important;
				}
				::v-deep .uv-search__action{
					font-size: var(--theme-df) !important;
				}
				::v-deep .uv-search__action::before{
					content: "|";
					color: #ADB0BD;
					position: relative;
					right: 20rpx;
					top: 0;
					z-index: 1000;
				}
			}
			.query-box{
				height: 88rpx;
				background-color: #FFFFFF;
				border-radius: 4rpx;
				display: flex;
				align-items: center;
				.query-item{
					width: 25%;
					display: flex;
					justify-content: center;
					align-items: center;
					gap: 6rpx;
					padding: 0 4rpx;
					&.small{
						width: 23%;
					}
					&.large{
						width: 27%;
					}
				}
			}
		}
		.app-content{
			width: 100%;
			height: calc(100% - 220rpx);
			.content-list{
				padding: 0 32rpx;
				display: flex;
				flex-direction: column;
				gap: 16rpx;
				.content-box{
					background: #FFFFFF;
					border-radius: 16rpx;
				}
			}
			.box-content{
				padding: 32rpx 32rpx 0;
				.box-head{
					display: flex;
					justify-content: space-between;
					align-items: center;
					gap: 10rpx;
					.head-code{
						font-weight: 600;
					}
					.head-status{
						display: flex;
						align-items: center;
						gap: 8rpx;
						.status-circle{
							width: 16rpx;
							height: 16rpx;
							border-radius: 16rpx;
							border: 4rpx solid #ADB0BD;
							background-color: #313233;
						}
						&.status-0{
							color: #EF7824;
							.status-circle{
								border-color: #FCE4D3;
								background-color: #EF7824;
							}
						}
						&.status-1{
							color: #2BD982;
							.status-circle{
								border-color: #D5F7E6;
								background-color: #2BD982;
							}
						}
						&.status-2{
							color: #F34D4D;
							.status-circle{
								border-color: #FDDBDB;
								background-color: #F34D4D;
							}
						}
					}
				}
				.box-time{
					margin-top: 24rpx;
					margin-bottom: 16rpx;
					background: #F2F7FC;
					border-radius: 8rpx;
					padding: 16rpx;
					color: #626466;
					display: flex;
					justify-content: space-between;
					align-items: center;
					gap: 10rpx;
					.time-status{
						padding: 10rpx 16rpx;
						border-radius: 48rpx;
						font-size: var(--theme-sm);
						line-height: var(--theme-sm-line);
						background-color: rgba(98,100,102,0.1);
						color: #ADB0BD;
						&.status-5{
							background-color: rgba(255,102,47,0.1);
							color: #FF662F;
						}
						&.status-4{
							background-color: rgba(43,217,130,0.1);
							color: #2BD982;
						}
					}
				}
				.box-info{
					margin-top: 8rpx;
					display: flex;
					align-items: center;
					gap: 8rpx;
					color: #626466;
					.info-item{
						width: calc(50% - 4rpx);
					}
				}
				.expand-more{
					padding: 24rpx 0;
					display: flex;
					justify-content: center;
					align-items: center;
					gap: 14rpx;
					color: #ADB0BD;
				}
			}
			.box-bottom{
				border-top: 2rpx solid #F0F1F3;
				display: flex;
				.bottom-btn{
					flex: 1;
					padding: 24rpx 0;
					text-align: center;
					color: #3E85D6;
					font-size: var(--theme-lg);
					line-height: var(--theme-lg-line);
				}
				.line{
					width: 2rpx;
					background-color: #F0F1F3;
				}
			}
		}
		.tree-popup{
			.popup-head{
				display: flex;
				align-items: center;
				gap: 8rpx;
				padding: 16rpx 32rpx;
				.btn{
					flex-shrink: 0;
					width: 100rpx;
					color: #909193;
					&.primary{
						color: $uv-primary;
						text-align: right;
					}
				}
				.text{
					flex: 1;
					text-align: center;
					font-size: var(--theme-lg);
					line-height: var(--theme-lg-line); 
				}
			}
			.tree-scroll{
				height: 400rpx;
				padding-top: 20rpx;
			}
		}
	}
</style>